﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using MiniX.API.Data;
using MiniX.Models;
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Senparc.CO2NET.Extensions;
using MiniX.Utility.Helper;

namespace MiniX.API.Controllers
{
    /// <summary>
    /// 访问量类，定义了CURD相关操作
    /// </summary>
    [Produces("application/json")]
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class VisitsController : BaseController<VisitsController>
    {
        /// <summary>
        /// VisitsController
        /// </summary>
        public VisitsController(MiniXApiContext context, IHttpContextAccessor httpContextAccessor) : base(context, httpContextAccessor)
        {

        }

        /// <summary>
        /// 新增访问量
        /// </summary>
        /// <param name="visits">构造访问量对象数据</param>
        /// <returns>返回新增的访问量</returns>          
        [HttpPost]
        [Route("/api/visits")]
        public async Task<IActionResult> Create(Visits visits)
        {
            try
            {
                // log.Information("visits=" + visits.ToJson());
                visits.created_at = DateTime.Now;
                visits.client_ip = Request.HttpContext.Connection.RemoteIpAddress!.MapToIPv4().ToString();
                _context.mini_visits.Add(visits);
                await _context.SaveChangesAsync();

                return Json(new { code = 0, msg = "success", data = visits });
            }
            catch (Exception ex)
            {
                log.Fatal(ex, " -> Create");
                return Json(new { code = 1, errcode = (int)ENUMHelper.ExceptionType.List, errmsg = ex.Message });
            }
        }

        /// <summary>
        /// 新增访问量-web
        /// </summary>
        /// <param name="visits">构造访问量对象数据</param>
        /// <returns>返回新增的访问量</returns>          
        [HttpPost]
        [Route("/api/visits/web")]
        public async Task<IActionResult> CreateFromWeb([FromForm]Visits visits)
        {
            try
            {
                // log.Information("visits=" + visits.ToJson());
                visits.created_at = DateTime.Now;
                visits.client_ip = Request.HttpContext.Connection.RemoteIpAddress!.MapToIPv4().ToString();
                _context.mini_visits.Add(visits);
                await _context.SaveChangesAsync();

                return Json(new { code = 0, msg = "success", data = visits });
            }
            catch (Exception ex)
            {
                log.Fatal(ex, " -> Create");
                return Json(new { code = 1, errcode = (int)ENUMHelper.ExceptionType.List, errmsg = ex.Message });
            }
        }
    }
}
